package com.powernobug.filter;

import com.powernobug.bean.vo.BaseRespVo;
import com.powernobug.util.JsonUtil;
import com.powernobug.util.JacksonUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();

        crossOrigin(request,response);

        boolean isLoginUri = uri.endsWith("/admin/auth/login");
        boolean isLogin = session.getAttribute("adminId") != null;

        if (uri.contains("/storage/create")) {
            filterChain.doFilter(request,response);
            return;
        }

        // 若用户访问登陆界面前来获取session，则直接放行
        // 若用户访问其他界面，每次访问都需要携带session，携带session的请求放行
        if (isLoginUri || isLogin) {
            filterChain.doFilter(request,response);
            return;
        }

        // 如果没有登录（无session访问），则响应请登录信息
        BaseRespVo baseRespVo = BaseRespVo.errList( 501);
        String jsonString = JsonUtil.writeJson(baseRespVo);
        response.getWriter().println(jsonString);
    }

    /**
     * 提供跨域的许可
     * @param request
     * @param response
     */
    private void crossOrigin(HttpServletRequest request, HttpServletResponse response) {
        // 是通过响应头提供的跨域许可
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        // 允许通过的请求头
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type,X-CskaoyanMarket-Admin-Token,X-CskaoyanMarket-Token");
        response.setHeader("Access-Control-Allow-Credentials","true");
    }

    @Override
    public void destroy() {}
}
